#!/usr/bin/python3

import os

def find_and_replace_in_makefile(root_dir, new_kerneldir):
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename == 'Makefile':
                makefile_path = os.path.join(dirpath, filename)
                with open(makefile_path, 'r') as f:
                    lines = f.readlines()

                with open(makefile_path, 'w') as f:
                    for line in lines:
                        if line.startswith('KERNELDIR'):
                            # 分割字符串以找到 KERNELDIR 后面的内容
                            parts = line.split('=', 1)
                            if len(parts) > 1:
                                # 替换 KERNELDIR 后面的内容
                                new_line = f'KERNELDIR={new_kerneldir}\n'
                            else:
                                # 如果原行中没有=，则添加=和新的 KERNELDIR
                                new_line = f'KERNELDIR={new_kerneldir} # Assuming no value was provided before\n'
                        else:
                            new_line = line
                        f.write(new_line)

# 主程序
if __name__ == "__main__":
    # 获取用户输入的 KERNELDIR 替换内容
    new_kerneldir = input("Enter the new KERNELDIR value: ")
    # 使用当前目录作为起始目录
    root_dir = os.getcwd()
    # 调用函数
    find_and_replace_in_makefile(root_dir, new_kerneldir)
    print("Makefile files have been updated with the new KERNELDIR value.")
